import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import cl.isc.webservice.ISC.*;

import java.io.*;
import java.util.*;
import java.net.*;

public class PremiumParse extends DefaultHandler
{
    boolean isContent_id;
    boolean isContent_name;
    boolean isContent_url;
    
    String image_url;
    String contents_url;
    
    Hashtable hData;
    Vector vContens;
    
    String[] aContent;
    
    public static void main( String[] args ){
    	PremiumParse mgr = new PremiumParse();
    	mgr.image_url = "images/";
    	mgr.contents_url = "/contents/main_include/";
    	if(args[0].equals("all")){
    		mgr.getAllContentList(args[1]);	
    	}else{
    		mgr.getContentList(args[0],args[1]);
	}
    }
	
    public PremiumParse(){}

    public void getAllContentList(String count){
    	try{
    	    ISC service = new ISCLocator();
            ISCPortType port = service.getISCPort();
            String xml = port.getAllContentList(Integer.parseInt(count));

    	    xmlParsing_start(xml);
    	    
    	    //return hData;   	    
    	    if(hData != null){
	    	if(hData.get("A1")!=null && ((Vector)hData.get("A1")).size() != 0)
	    	    writeRingtone((Vector)hData.get("A1"));
	    		
	    	if(hData.get("07")!=null && ((Vector)hData.get("07")).size() != 0){
	    	    writeImage((Vector)hData.get("07"),"07");
	    	}else if(hData.get("08")!= null && ((Vector)hData.get("08")).size() != 0){
	            writeImage((Vector)hData.get("08"),"08");
	    	}
	    	
	    	if(hData.get("04")!=null && ((Vector)hData.get("04")).size() != 0)
	    	    writeGame((Vector)hData.get("04"));
	     }
    	    
    	    /*
    	    if(hData != null){
	    	if(hData.get("A1")!=null)
	    	    writeRingtone((Vector)hData.get("A1"));
	    		
	    	if(hData.get("07")!=null){
	    	    writeImage((Vector)hData.get("07"),"07");
	    	}else if(hData.get("08")!= null){
	            writeImage((Vector)hData.get("08"),"08");
	    	}
	    	
	    	if(hData.get("04")!=null)
	    	    writeGame((Vector)hData.get("04"));
	     }
	     */
    	}catch(Exception e){
    		System.out.println(e.toString());
    	}
    }
    
    public void getContentList(String mcate_cd , String count){
    	try{
    	    ISC service = new ISCLocator();
            ISCPortType port = service.getISCPort();
            String xml = port.getContentList(mcate_cd, Integer.parseInt(count));
            
    	    xmlParsing_start(xml);
    	}catch(Exception e){
    		System.out.println(e.toString());
    	}
    }
    
    public void xmlParsing_start(String xml){  
    	try{
    	    SAXParserFactory  factory = SAXParserFactory.newInstance( );
            SAXParser parser = factory.newSAXParser();
    	    byte[] bxml=xml.getBytes("UTF-8");
    	    ByteArrayInputStream is = new ByteArrayInputStream(bxml);
            parser.parse(is, this);
    	    /*
            SAXParserFactory  factory = SAXParserFactory.newInstance( );
            SAXParser parser = factory.newSAXParser();
            byte[] bxml=xml.getBytes();
	    ByteArrayInputStream is = new ByteArrayInputStream(bxml);
            parser.parse(is, this);*/
            //parser.parse("/home02/applications/batch/home/chl_home/xml_test.xml",this);
        }catch(Exception e){
            System.out.println("xmlParsing_start Exception: " +e.toString());
        }
    }
    
    public void startDocument() throws SAXException{}

    public void endDocument() throws SAXException {}
	
    public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException{
    	if(qName.equals("CONTENTS")){
    		vContens = new Vector();
    	}else if(qName.equals("ALL_CONTENTS")){
    		hData = new Hashtable();
    	}else if(qName.equals("RINGTONES")){		
    		vContens = new Vector();
    	}else if(qName.equals("WALLPAPERS")){
    		vContens = new Vector();
    	}else if(qName.equals("SCREENSAVERS")){
    		vContens = new Vector();
	}else if(qName.equals("GAMES")){
		vContens = new Vector();
    	}else if(qName.equals("CONTENT")){
    		aContent = new String[3];
    	}else if(qName.equals("CONTENT_ID")){
    		isContent_id = true;
    	}else if(qName.equals("CONTENT_NAME")){    		
    		isContent_name = true;
    	}else if(qName.equals("PREVIEW_URL")){    		
    		isContent_url = true;
    	}
    }
	
    public void endElement(String uri,String localName, String qName) throws SAXException{
    	if(qName.equals("CONTENTS")){
    		
    	}else if(qName.equals("ALL_CONTENTS")){
    		
    	}else if(qName.equals("RINGTONES")){
    		hData.put("A1", vContens); 
    		vContens = null;
    	}else if(qName.equals("WALLPAPERS")){
    		hData.put("08", vContens); 
    		vContens = null;
    	}else if(qName.equals("SCREENSAVERS")){
    		hData.put("07", vContens);
    		vContens = null;
	}else if(qName.equals("GAMES")){
		hData.put("04", vContens);
    		vContens = null;
    	}else if(qName.equals("CONTENT")){	
    		vContens.add(aContent);
    		aContent = null;		
    	}else if(qName.equals("CONTENT_ID")){
    		isContent_id = false;
    	}else if(qName.equals("CONTENT_NAME")){
    		isContent_name = false;
    	}else if(qName.equals("PREVIEW_URL")){    		
    		isContent_url = false;
    	}
    }
	
    public void characters( char[] ch, int start, int len ){
	if(isContent_id){
	    aContent[0] = new String(ch, start, len )  == null? "" : new String(ch, start, len );
	}else if(isContent_name){
	    aContent[1] = new String(ch, start, len )  == null? "" : new String(ch, start, len );
	}else if(isContent_url){
	    aContent[2] = new String(ch, start, len )  == null? "" : new String(ch, start, len );
	}
    }

    public void ignorableWhitespace(char ch[], int start, int length ) throws SAXException{}
	
	public String getFile(String sUrl, String mcate){
	    String file_name = "";
	    try{
            URL url= new URL(sUrl); 
            String img_tmp= sUrl.substring(sUrl.lastIndexOf("."));
            file_name = mcate + img_tmp;
            BufferedInputStream bin = new BufferedInputStream(url.openStream()); 
            int cnt;
            String dir = "/home02/applications/batch/home/chl_home/log/"+getDate("yyyyMMdd")+"/"+file_name;
            FileOutputStream fos = new FileOutputStream(dir);
            while((cnt=bin.read())!=-1 ){ 
                fos.write(cnt); 
            } 
            bin.close(); 
            fos.close();
        }catch(Exception e){
            System.out.println(e.toString());
        }
        return file_name;
	}
	
    public void writeRingtone(Vector ringtones){
        try{
            int count = 0;
    	    if(ringtones != null){
    	    	if(ringtones.size() > 3){
    	    	    count = 3;
    	    	}else{
    	    	    count = ringtones.size();
        		}
    	    }
    	    if(ringtones != null && ringtones.size() > 0){
                StringBuffer stContent = new StringBuffer();
	            stContent.append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"199\"> \n")
	                     .append("  <tr>\n")
	                     .append("    <td colspan=\"3\"><img src=\""+image_url+"main_tt_01.gif\" border=\"0\"></td>\n")
	                     .append("  </tr>\n")
	                     .append("  <tr>\n")
	                     .append("    <td colspan=\"3\" height=\"1\" bgcolor=\"#B2B2B2\"></td>\n")
	                     .append("  </tr>\n");
    	        for(int i=0; i<count; i++){
    		        String[] aRingtone = (String[])ringtones.elementAt(i);  
		            String color = (i%2 == 1)? "#FFFFFF":"#F5F5F5";   
                    stContent.append("  <tr bgcolor=\""+color+"\">\n")
                             .append("    <td width=\"23\" height=\"23\" align=\"center\">"+(i+1)+"</td>\n")
                             .append("    <td width=\"144\"><div style=\"padding-left:3px;\"><a href=\"./play/goPremium.jsp?mcate_cd=A1&content_id="+aRingtone[0]+"\">"+sub_string(aRingtone[1],20)+"</a></div></td>\n")
                             .append("    <td width=\"25\">\n")
                             .append("    	<a href=\"#\" ONCLICK=\"javascript:window.open('play/popup_play.jsp?filepath="+aRingtone[2]+"','new','location=no,directories=no,resizable=no,status=no,toolbar=no,menubar=no,width=144,height=106,scrollbars=auto');return false\">\n")
                             .append("    	<img src=\""+image_url+"butn_play_01.gif\" border=\"0\"></a></td>\n")
                             .append("  </tr>\n");
            		if(i+1 != count){
            		    stContent.append("  <tr>\n")
                                 .append("    <td colspan=\"3\" height=\"1\" bgcolor=\"#DBDADA\"></td>\n")
                                 .append("  </tr>\n");
            		}
	            }
                stContent.append("  <tr>\n")
                         .append("    <td colspan=\"3\" height=\"1\" bgcolor=\"#B2B2B2\"></td>\n")
                         .append("  </tr>\n")
                         .append("  <tr>\n")
                         .append("  </tr>\n")
                         .append("  <tr>\n")
                         .append("    <td colspan=\"3\" align=\"right\" height=\"21\" valign=\"top\">\n")
                         .append("      <a href=\"javascript:goMenu('play','01');\"><img src=\""+image_url+"main_butn_more01.gif\" border=\"0\"></a>\n")
                         .append("    </td>\n")
                         .append("  </tr>\n")
                         .append("</table>\n");
                PrintWriter out = new PrintWriter( 
                                     new OutputStreamWriter(
                                       new FileOutputStream("/home02/applications/batch/home/chl_home/log/"+getDate("yyyyMMdd")+"/ringtone_include.html", false), "UTF-8"), true);
                out.println(stContent.toString());
                out.close();
                out = null;
            }
        }catch(Exception e){
            System.out.println("PremiumPase.writeRingtone() File Write Exception : "+ e.toString());
        }
    }
    
    public void writeGame(Vector games){
        try
        {
            int count = 0;
    	    if(games != null){
    	    	if(games.size() > 4){
    	    	    count = 4;
    	    	}else{
    	    	    count = games.size();
        		}
    	    }
            if(games != null && games.size() > 0){
                StringBuffer stContent = new StringBuffer();
       	    	String[] aGame1 = (String[])games.elementAt(0);
       	    	String preFile = getFile(aGame1[2], "javagame");
	    	    stContent.append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"199\">\n")
                         .append("    <tr>\n")
                         .append("        <td colspan=\"2\"> <img src=\""+image_url+"main_tt_03.gif\"></td>\n")
                         .append("    </tr>\n")
                         .append("    <tr>\n")
                         .append("        <td width=\"96\" valign=\"top\">\n")
                         .append("            <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n")
                         .append("            <tr>\n")
                         .append("                <td width=\"91\" height=\"98\" valign=\"top\" background=\""+image_url+"mobilegame_bg.gif\">\n")
                         .append("                    <table width=\"84\" height=\"91\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n")
                         .append("                        <tr>\n")
                         .append("                            <td width=\"7\" height=\"14\"></td>\n")
                         .append("                            <td width=\"74\">&nbsp;</td>\n")
                         .append("                        </tr>\n")
                         .append("                        <tr>\n")
                         .append("                            <td width=\"7\">&nbsp;</td>\n")
                         .append("                            <td><a href=\"./play/goPremium.jsp?mcate_cd=04&content_id="+aGame1[0]+"\"><img src=\""+contents_url+preFile+"\" width=\"77\" height=\"77\" border=\"0\"></a></td>\n")
                         .append("                        </tr>\n")
                         .append("                    </table>\n")
                         .append("                </td>\n")
                         .append("            </tr>\n")
                         .append("            </table>\n")
                         .append("        </td>\n")
                         .append("        <td width=\"103\" valign=\"top\">\n")
                         .append("            <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n")
                         .append("                <tr>\n")
                         .append("                    <td width=\"103\" height=\"1\" bgcolor=\"B4B4B4\"></td>\n")
                         .append("                </tr>\n")
                         .append("                <tr>\n")
                         .append("                    <td height=\"78\" valign=\"top\">\n")
                         .append("                        <table height=\"64\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n")
                         .append("                            <tr>\n")
                         .append("                                <td width=\"10\" valign=\"top\"><img src=\""+image_url+"icon/main_icon_03.gif\" width=\"3\" height=\"5\" alt=\"\" border=\"0\" align=\"absmiddle\" vspace=\"5\"></td>\n")
                         .append("                                <td width=\"102\"><a href=\"./play/goPremium.jsp?mcate_cd=04&content_id="+aGame1[0]+"\">"+sub_string(aGame1[1],10)+"</a></td>\n")
                         .append("                            </tr>\n");
    	        for(int i=1; i<count; i++){
        		    String[] aGame = (String[])games.elementAt(i);                           
                    stContent.append("                            <tr>\n")
                             .append("                                <td width=\"10\" valign=\"top\"><img src=\""+image_url+"icon/main_icon_03.gif\" width=\"3\" height=\"5\" alt=\"\" border=\"0\" align=\"absmiddle\" vspace=\"5\"></td>\n")
                             .append("                                <td width=\"102\"><a href=\"./play/goPremium.jsp?mcate_cd=04&content_id="+aGame[0]+"\">"+sub_string(aGame[1],10)+"</a></td>\n")
                             .append("                            </tr>\n");
        	    }
                stContent.append("                        </table>\n")
                         .append("                    </td>\n")
                         .append("                </tr>\n")
                         .append("                <tr>\n")
                         .append("                    <td height=\"16\" align=\"right\"><a href=\"javascript:goMenu('play','03');\"><img src=\""+image_url+"main_butn_more01.gif\" border=\"0\"></a></td>\n")
                         .append("                </tr>\n")
                         .append("                <tr>\n")
                         .append("                    <td height=\"1\" bgcolor=\"B4B4B4\"></td>\n")
                         .append("                </tr>\n")
                         .append("            </table>\n")
                         .append("        </td>\n")
                         .append("    </tr>\n")
                         .append("</table>\n");
                PrintWriter out = new PrintWriter( 
                                     new OutputStreamWriter(
                                       new FileOutputStream("/home02/applications/batch/home/chl_home/log/"+getDate("yyyyMMdd")+"/javagame_include.html", false), "UTF-8"), true);
                out.println(stContent.toString());
                out.close();
                out = null;
            }
        }catch(Exception e){
            System.out.println("PremiumPase.writeGame() File Write Exception : "+ e.toString());
        }
    }
    
    public void writeImage(Vector images, String mcate_cd){
        try{
    	    int count = 0;
    	    if(images != null){
    	    	if(images.size() > 4){
    	    	    count = 4;
    	    	}else{
    	    	    count = images.size();
        		}
    	    }
    	    if(images != null && images.size() > 0){
    	    	String[] aImage1 = (String[])images.elementAt(0);
    	    	String preFile = getFile(aImage1[2], "image");
    	    	StringBuffer stContent = new StringBuffer();
                stContent.append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"199\">\n")
                         .append("    <tr>\n")
                         .append("        <td colspan=\"2\"> <img src=\""+image_url+"main_tt_04.gif\"></td>\n")
                         .append("    </tr>\n")
                         .append("    <tr>\n")
                         .append("        <td width=\"96\" valign=\"top\">\n")
                         .append("            <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n")
                         .append("            <tr>\n")
                         .append("                <td width=\"91\" height=\"98\" valign=\"top\" background=\""+image_url+"colorimage_bg.gif\">\n")
                         .append("                    <table width=\"84\" height=\"91\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n")
                         .append("                        <tr>\n")
                         .append("                            <td width=\"7\" height=\"14\"></td>\n")
                         .append("                            <td width=\"74\">&nbsp;</td>\n")
                         .append("                        </tr>\n")
                         .append("                        <tr>\n")
                         .append("                            <td width=\"7\">&nbsp;</td>\n")
                         .append("                            <td><a href=\"./play/goPremium.jsp?mcate_cd="+mcate_cd+"&content_id="+aImage1[0]+"\"><img src=\""+contents_url+preFile+"\" width=\"77\" height=\"77\" border=\"0\"></a></td>\n")
                         .append("                        </tr>\n")
                         .append("                    </table>\n")
                         .append("                </td>\n")
                         .append("            </tr>\n")
                         .append("            </table>\n")
                         .append("        </td>\n")
                         .append("        <td width=\"103\" valign=\"top\">\n")
                         .append("            <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n")
                         .append("                <tr>\n")
                         .append("                    <td width=\"103\" height=\"1\" bgcolor=\"B4B4B4\"></td>\n")
                         .append("                </tr>\n")
                         .append("                <tr>\n")
                         .append("                    <td height=\"78\" valign=\"top\">\n")
                         .append("                        <table height=\"64\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n")
                         .append("                            <tr>\n")
                         .append("                                <td width=\"10\" valign=\"top\"><img src=\""+image_url+"icon/main_icon_03.gif\" width=\"3\" height=\"5\" alt=\"\" border=\"0\" align=\"absmiddle\" vspace=\"5\"></td>\n")
                         .append("                                <td width=\"102\"><a href=\"./play/goPremium.jsp?mcate_cd="+mcate_cd+"&content_id="+aImage1[0]+"\">"+sub_string(aImage1[1],10)+"</a></td>\n")
                         .append("                            </tr>\n");
                for(int i=1; i<count; i++){
    		        String[] aImage = (String[])images.elementAt(i);
                    stContent.append("                            <tr>\n")
                             .append("                                <td width=\"10\" valign=\"top\"><img src=\""+image_url+"icon/main_icon_03.gif\" width=\"3\" height=\"5\" alt=\"\" border=\"0\" align=\"absmiddle\" vspace=\"5\"></td>\n")
                             .append("                                <td width=\"102\"><a href=\"./play/goPremium.jsp?mcate_cd="+mcate_cd+"&content_id="+aImage[0]+"\">"+sub_string(aImage[1],10)+"</a></td>\n")
                             .append("                            </tr>\n");
                }                                                                                                                                                                                                        
                stContent.append("                        </table>\n")
                         .append("                    </td>\n")
                         .append("                </tr>\n")
                         .append("                <tr>\n")
                         .append("                    <td height=\"16\" align=\"right\"><a href=\"javascript:goMenu('play','02');\"><img src=\""+image_url+"main_butn_more01.gif\" border=\"0\"></a></td>\n")
                         .append("                </tr>\n")
                         .append("                <tr>\n")
                         .append("                    <td height=\"1\" bgcolor=\"B4B4B4\"></td>\n")
                         .append("                </tr>\n")
                         .append("            </table>\n")
                         .append("        </td>\n")
                         .append("    </tr>\n")
                         .append("</table>\n");
                PrintWriter out = new PrintWriter( 
                                     new OutputStreamWriter(
                                       new FileOutputStream("/home02/applications/batch/home/chl_home/log/"+getDate("yyyyMMdd")+"/image_include.html", false), "UTF-8"), true);
                out.println(stContent.toString());
                out.close();
                out = null;
            }
        }catch(Exception e){
            System.out.println("PremiumPase.writeImage() File Write Exception : "+ e.toString());
        }
    }
    
    public String getDate(String str_format){
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(str_format);
        java.util.Date currentTime = new java.util.Date();
        return formatter.format(currentTime);
    }
    
    public String sub_string(String s, int i)
    {
        int title_length = (s.length() >= i) ? i : s.length();

        s = s.substring(0,title_length);
        return (s.length() < i) ? s : s+"..";
    }

}